/*
Problem:    Combination Sum II
Notes:
Given a collection of candidate numbers (C) and a target number (T), find all unique
 combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … ,ak) must be in non-descending order.
(ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
*/

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
    	sort(num.begin(), num.end());
    	vector<int> candidates;
    	vector<int> count;
    	for (int i = 0; i < num.size(); ++i) {
    		if (i == 0) {
    			candidates.push_back(num[i]);
    			count.push_back(1);
    		} else {
    			if (candidates.back() == num[i]) {
    				count.back()++;
    			} else {
    				candidates.push_back(num[i]);
    				count.push_back(1);
    			}
    		}
    	}

    	vector<vector<int> > result;
		vector<int> items;
		FindPartialSum(candidates, target, count, 0, 0, &items, &result);
		return result;
    }

    void FindPartialSum(const vector<int>& candidates, int target, vector<int>& count, int sum, 
			int last_index, vector<int>* items, vector<vector<int> >* result) {
		if (sum == target) {
			result->push_back(*items);
			return;
		}

		for (int i = last_index; i < candidates.size(); i++) 
			if (count[i] > 0 && sum + candidates[i] <= target) {
				count[i]--;
				items->push_back(candidates[i]);
				FindPartialSum(candidates, target, count, sum + candidates[i], i, items, result);
				count[i]++;
				items->pop_back();

			}
	}
};

int main(int argc, char* argv[])
{
	int a[] = {10, 1, 2, 7, 6, 1, 5};
	vector<int> input;
	for (int i = 0; i < 7; i++)
		input.push_back(a[i]);

	Solution s;	
	vector<vector<int> > result = s.combinationSum2(input, 8);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++)
			cout << result[i][j] << " ";
		cout << endl;
	}
	
	return 0;
}